package processor;

import com.idol.web.bean.Request;
import com.idol.web.bean.Response;
import com.idol.web.container.ServletContainer;
import com.idol.web.servlet.http.HttpServlet;
import com.idol.web.util.StaticResourceUtil;

import java.net.Socket;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className processor.RequestProcessor
 * @description 请求处理器
 * @date 2020/11/20 22:33
 **/
public class RequestProcessor extends Thread {
    private Socket socket;
    private ServletContainer container;

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());
            if (container.containsKey(request.getWebName(), request.getResourcePath())) {
                HttpServlet httpServlet = container.get(request.getWebName(), request.getResourcePath());
                httpServlet.service(request, response);
            } else {
                String fileAbsolutePath = StaticResourceUtil.getFileAbsolutePath(request.getWebName(), request.getResourcePath());
                response.outPutHtml(fileAbsolutePath);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public RequestProcessor(Socket socket, ServletContainer servletContainer) {
        this.socket = socket;
        this.container = servletContainer;
    }
}
